package cn.dubito.miaosha.service;

import cn.dubito.miaosha.dao.OrderDao;
import cn.dubito.miaosha.domain.OrderInfo;
import cn.dubito.miaosha.domain.SeckillOrder;
import cn.dubito.miaosha.domain.SeckillUser;
import cn.dubito.miaosha.redis.OrderKey;
import cn.dubito.miaosha.redis.RedisService;
import cn.dubito.miaosha.vo.GoodsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author liliang
 * @description:
 * @date 2018/3/31.
 */
@Service
public class OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private RedisService redisService;

    public SeckillOrder getSeckillOrderByUserIdAndGoodsId(long userId, long goodsId) {
        SeckillOrder seckillOrder = redisService.get(OrderKey.getSeckillOrderByUserIdAndGoodsId, userId + "_" + goodsId, SeckillOrder.class);
        if (seckillOrder != null) {
            return seckillOrder;
        }
        seckillOrder = orderDao.getSeckillOrderByUserIdAndGoodsId(userId, goodsId);
        if (seckillOrder != null) {
            redisService.set(OrderKey.getSeckillOrderByUserIdAndGoodsId, userId + "_" + goodsId, seckillOrder);
        }
        return seckillOrder;
    }

    public OrderInfo getOrderById(long orderId) {
        return orderDao.getOrderById(orderId);
    }

    @Transactional(rollbackFor = Exception.class)
    public OrderInfo createOrder(SeckillUser user, GoodsVO goods) {

        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCreateDate(new Date());
        orderInfo.setDeliveryAddrId(0L);
        orderInfo.setGoodsCount(1);
        orderInfo.setGoodsId(goods.getId());
        orderInfo.setGoodsName(goods.getGoodsName());
        orderInfo.setGoodsPrice(goods.getSeckillPrice());
        orderInfo.setOrderChannel(1);
        orderInfo.setStatus(0);
        orderInfo.setUserId(user.getId());
        orderDao.insert(orderInfo);

        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setUserId(user.getId());
        seckillOrder.setGoodsId(goods.getId());
        seckillOrder.setOrderId(orderInfo.getId());
        orderDao.insertSeckillOrder(seckillOrder);
        redisService.set(OrderKey.getSeckillOrderByUserIdAndGoodsId, user.getId() + "_" + goods.getId(), seckillOrder);

        return orderInfo;
    }

}
